﻿

using System.ComponentModel;
using System.IO.IsolatedStorage;
using System;
namespace HelperControls.Utils
{
    public class MySettings : INotifyPropertyChanged
    {
        //klucze dla ustawień
        readonly string LanguageSettingKeyName = "LanguageSetting";

        //wartości domyślne ustawień
        string LanguageSettingDefault = Constants.LANG_EN;


        private IsolatedStorageSettings settings;

        public MySettings()
        {
            if (!DesignerProperties.IsInDesignTool)
            {
                settings = IsolatedStorageSettings.ApplicationSettings;
            }
        }


        #region metody do pobierania/zapisywania/aktualizacji ustawien

        //metoda do dodawania bądź aktualizacji pojedynczego ustawienia
        public bool AddOrUpdateValue(string key, Object value)
        {
            bool valueChanged = false;

            if (settings.Contains(key))
            {
                if (settings[key] != value)
                {
                    settings[key] = value;
                    valueChanged = true;
                }
            }
            else
            {
                settings.Add(key, value);
                valueChanged = true;
            }
            return valueChanged;
        }

        //metoda do pobrania pojedynczego ustawienia
        public T GetValueOrDefault<T>(string key, T defaultValue)
        {
            T value;

            if (settings.Contains(key))
            {
                value = (T)settings[key];
            }
            else
            {
                value = defaultValue;
            }
            return value;
        }

        public void Save(string property)
        {
            settings.Save();
            OnPropertyChanged(property);
        }

        #endregion

        #region PropertyChanged
        public event PropertyChangedEventHandler PropertyChanged;

        protected void OnPropertyChanged(string name)
        {
            if (PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs(name));
            }
        }
        #endregion

        public string LanguageSetting
        {
            get
            {
                return GetValueOrDefault<string>(LanguageSettingKeyName, LanguageSettingDefault);
            }
            set
            {
                if (AddOrUpdateValue(LanguageSettingKeyName, value))
                {
                    Save("LanguageSetting");
                }
            }
        }
    }
}
